﻿using System;
using System.Windows.Forms;
using System.Threading;

namespace desktop.HelperForms
{
    public partial class SplashForm : Form
    {
        private static Thread _runThread;
        private static SplashForm _sp;

        private delegate void CloseFormDelegate();
        private delegate void SetStatusDelegate(string s);

        private CloseFormDelegate _closeFormDelegate;
        private SetStatusDelegate _setStatusDelegate;

        private static string _text = "Loadiranje..";

        private SplashForm()
        {
            InitializeComponent();
            _closeFormDelegate = _closeForm;
            _setStatusDelegate = _setStatus;
        }

        public static void StartSplashScreen()
        {
            _runThread = new Thread(new ThreadStart(_showForm));
            _runThread.IsBackground = true;
            _runThread.Start();
        }

        public static void EndSplashScreen()
        {
            _sp.Invoke(_sp._closeFormDelegate);
            _runThread.Join();

            _runThread = null;
            _sp = null;
        }


        public static void SetStatus(string status)
        {
            _text = status;
            if (_sp != null)
            {
                _sp.Invoke(_sp._setStatusDelegate, status);
            }
        }


        private static void _showForm()
        {
            _sp = new SplashForm();
            Application.Run(_sp);
        }

        private void _closeForm()
        {
            _sp.Close();
        }

        private void _setStatus(string s)
        {
            _sp.statusLabel.Text = s;
            _sp.Update();
        }

        protected override void OnLoad(EventArgs e)
        {
            statusLabel.Text = _text;
            base.OnLoad(e);
        }
    }
}
